package com.example.bookstore.config.filter

import com.example.bookstore.security.MyUserDetailsService
import com.example.bookstore.security.TokenService
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest


/**
 * Created by IntelliJ IDEA.
 * User: lvshe
 * Date: 2019/8/13
 * Time: 19:37
 */
class TokenVerifyFilter(private val tokenService: TokenService, private val userDetailsService: MyUserDetailsService) : GenericFilterBean() {


    override fun doFilter(req: ServletRequest, res: ServletResponse, filterChain: FilterChain) {
        val request = req as HttpServletRequest
        val username = tokenService.parseUsernameFromToken(request)
        if (username != null) {
            val userDetails = userDetailsService.loadUserByUsername(username)
            SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)
        } else {
            SecurityContextHolder.getContext().authentication = null
        }
        filterChain.doFilter(req, res)
    }


}